// Description  :
// Author       : MMingzhao
// Date         : 2020-01-15 17:55

// Package api
package api

import (
	"github.com/gin-gonic/gin"
	"go-admin-template/pkg/errors"
	"go-admin-template/pkg/handler"
	"go-admin-template/router/entity"
	"go-admin-template/service"
	"go-admin-template/tools"
)

//AddUser 添加用户信息
func AddUser(ctx *gin.Context) {

	userDto := entity.User{}
	if err := ctx.BindJSON(&userDto); err != nil {
		handler.SendResponse(ctx, errors.InternalServerError, nil)
		return
	}

	msgs := validation(userDto)
	if len(msgs) > 0 {
		handler.SendResponse(ctx, errors.ErrValidation, msgs)
		return
	}

	// 校验通过，保存
	service.SaveUser(userDto)

	handler.SendResponse(ctx, errors.OK, nil)
}

//UserList 获取所有用户
func UserList(ctx *gin.Context) {

	userList := service.UserList()
	handler.SendResponse(ctx, errors.OK, userList)
}

func validation(user entity.User) []entity.ValidationMsg {

	// 存储校验失败消息
	msgs := []entity.ValidationMsg{}

	// 判空
	if user.Username == "" {
		msgs = append(msgs, entity.ValidationMsg{
			Msg: "用户名称不可为空",
		})
		return msgs
	}
	if user.Mobile == "" {
		msgs = append(msgs, entity.ValidationMsg{
			Msg: "用户手机不可为空",
		})
		return msgs
	}
	if user.Password == "" {
		msgs = append(msgs, entity.ValidationMsg{
			Msg: "密码不可为空",
		})
		return msgs
	}

	// 校验手机号码
	if !tools.ValidationMobile(user.Mobile) {
		msgs = append(msgs, entity.ValidationMsg{
			Msg: "用户手机号码校验位通过",
		})
		return msgs
	}

	// 判断是否存在数据库中
	isExist, _ := service.FindByUsername(user.Username)
	if !isExist {
		msgs = append(msgs, entity.ValidationMsg{
			Msg: "用户名已被占用",
		})
		return msgs
	}

	return msgs
}
